#include "stdafx.h"
#include "SOCK_Acceptor.h"

namespace Network
{
	//Use to store the existing socket
	SOCK_Acceptor::SOCK_Acceptor(const SOCKET &addr) {	
		handle_ = addr; 
		
		if (handle_ == INVALID_SOCKET) {
			fprintf(stdout, "Socket is invalid\n");
		}
	}

	//Use to create a new socket and start listening on it
	SOCK_Acceptor::SOCK_Acceptor(const INET_Addr &addr) {	
		//Create socket
		handle_ = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
		
		if (handle_ == INVALID_SOCKET) {
			fprintf(stdout, "Cannot create listening socket\n");
			return;
		}

		//Bind socket
		sockaddr_in clientSocket = *addr.Addr();
		int result = bind(handle_, (SOCKADDR *)&clientSocket, sizeof(clientSocket));	
		if(result == SOCKET_ERROR){
			fprintf(stdout, "Cannot bind listening socket\n");
			return;
		}

		// Start listening on endpoint; Use maximum length of pending queue;
		// See: http://msdn.microsoft.com/en-us/library/ms739168%28v=vs.85%29.aspx
		result = listen(handle_, SOMAXCONN);
		if(result == SOCKET_ERROR){
			fprintf(stdout, "Cannot listen on listening socket\n");
			return;
		}
	}

	void SOCK_Acceptor::accept(SOCK_Stream &s)
	{
		//fprintf(stdout, "Accepting connection from client\n");
		s.set_handle( ::accept(handle_, 0, 0));
	}

	SOCKET SOCK_Acceptor::get_handle(){
		return handle_;
	}

	SOCK_Acceptor::~SOCK_Acceptor(void)
	{
		//empty destructor
	}
}